package 算法.base.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lchenglong
 * @date 2022/5/3
 */
public class CyclicBarrierTest {
    static class TaskThread extends Thread {

        java.util.concurrent.CyclicBarrier barrier;

        public TaskThread(java.util.concurrent.CyclicBarrier barrier) {
            this.barrier = barrier;

        }

        @Override
        public void run() {
            try {
                while (counter.get()>0){
                    Thread.sleep(1000);
                    System.out.println("站牌新到一人.");
                    barrier.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int threadNum = 2;
        java.util.concurrent.CyclicBarrier barrier = new java.util.concurrent.CyclicBarrier(threadNum, new Runnable() {

            @Override
            public void run() {
                System.out.println("人满发车>>>>>>>>>>>>>>🚗");
                counter = new AtomicInteger(2);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("公交车已到达");
            }
        });

        for(int i = 0; i < threadNum; i++) {
            new TaskThread(barrier).start();
        }
    }
    public static AtomicInteger counter = new AtomicInteger(2);

    public static void count(){
        counter.decrementAndGet();
    }
}
